package com.lz.specification.concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadLocal doc案例
 *
 * @author: li
 * @date: 2019/1/17
 */
public class ThreadLocalDemo03 {

    private static final AtomicInteger nextId = new AtomicInteger(1000);
    private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 1000;
        }
    };

    public static int get() {
        return nextId.getAndIncrement();
        // return threadId.get();
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int i1 = ThreadLocalDemo03.get();
                System.out.println(Thread.currentThread().getName() + " : " + i1);
            }).start();
        }

        TimeUnit.SECONDS.sleep(1);
        System.out.println("分割线");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                Integer integer = threadId.get();
                int i1 = integer + 1;
                threadId.set(i1);
                System.out.println(Thread.currentThread().getName() + " : " + i1);
            }).start();
        }

    }
}


